<?php

namespace App\Model;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Number extends BaseModel
{
    protected $table = 'user';
    protected $chatLog_table = 'chat_log';
    protected $audit_table = 'audit_user_img_log';
    protected $finance_rant = 'finance_wealth_rank';
    protected $union_signing = 'union_signing';
    protected $set_table = 'user_set';
    protected $login_table = 'user_active';
    protected $recharge_limit_table = 'user_recharge_limit';
    protected $user_lgoin_log_table = 'user_login_log';
    protected $primaryKey = 'user_id';
    public $timestamps = false;
    private $fields = [
        'user_id',
        'mobile_phone',
        'portrait',
        'gender',
        'create_timestamp',
        'is_block',
        'guid',
        'uuid',
        'nickname',
        'liang',
        'super',
        'official',
        'waiter',
        'active_certify',
        'v',
        'v_desc',
        'is_abnormal',
        'is_open_code',
        'code'
    ];
    const DEFAULT_HEAD_IMG = '/room/image_default.png';
    public $forbidUser = [];   // 封号列表

    public function financeWallet()
    {
        return $this->hasOne(FinanceWallet::class, 'user_id', 'user_id');
    }

    public function FriendsFollow()
    {
        return $this->hasMany(FriendsFollow::class, 'user_id', 'user_id');
    }

    public function FriendsFans()
    {
        return $this->hasMany(FriendsFollow::class, 'follow_user_id', 'user_id');
    }

    public function financeWithdrawOrder()
    {
        return $this->hasMany(FinanceWithdrawOrder::class, 'user_id', 'user_id');
    }

    public function room()
    {
        return $this->hasOne(Room::class, 'user_id', 'user_id');
    }

    public function activeCertifyModel()
    {
        return $this->hasOne(ActiveCertify::class, 'user_id', 'user_id');
    }

    public function getPortraitAttribute($value)
    {
        if (!$value)
            return $this->defaultHeadImg();
        $value = json_decode($value, true);
        if (!empty($value)) {
            if (strpos($value[0], 'http:') !== false || strpos($value[0], 'https:') !== false) {
                return $value[0];
            } elseif (strpos($value[0], 'qqapp') !== false) {
                return $this->defaultHeadImg();
            } {
                return $this->getOSSUrl() . $value[0];
            }
        }
    }

    public function getCreateTimestampAttribute($value)
    {
        if (!$value)
            return 0;
        return date('Y-m-d H:i:s', $value);
    }

    /**
     * 会员列表
     * @param Request $request
     * @return mixed
     */
    public function getList(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $sort = $request->get('sort', 'asc');
        $uuid = $request->get('uuid', null);
        $user_id = $request->get('user_id', null);
        $nickname = $request->get('nickname', null);
        $mobile_phone = $request->get('mobile_phone', null);
        $is_block = $request->get('is_block', null);          // 0 正常 1 已封号
        $liang = $request->get('liang', null);
        $super = $request->get('super', null);
        $waiter = $request->get('waiter', null);
        $official = $request->get('official', null);
        $active_certify = $request->get('active_certify', null);

        $query = new Number();
        if ($uuid)
            $query = $query->where('user.uuid', $uuid);
        if ($user_id)
            $query = $query->where('user.user_id', $user_id);
        if ($mobile_phone)
            $query = $query->where('user.mobile_phone', 'like', "%$mobile_phone%");
        if ($nickname)
            $query = $query->where('user.nickname', 'like', "%$nickname%");
        if (isset($active_certify))
            $query = $query->where('user.active_certify', $active_certify);
        if (isset($is_block)) {
            self::getForbidList();
            if (!empty($this->forbidUser)) {
                $user_ids = array_keys($this->forbidUser);
                if ($is_block == 0) {
                    $query = $query->whereNotIn('user.user_id', $user_ids);
                } elseif ($is_block == 1) {
                    $query = $query->whereIn('user.user_id', $user_ids);
                }
            }
        }
        if (isset($liang))
            $query = $query->where('user.liang', $liang);
        if (isset($super))
            $query = $query->where('user.super', $super);
        if (isset($waiter))
            $query = $query->where('user.waiter', $waiter);
        if (isset($official))
            $query = $query->where('user.official', $official);

        $data = $query->leftJoin('union_user', 'union_user.user_id', '=', $this->table . '.user_id')
            ->leftJoin('union', 'union.id', '=', 'union_user.un_id')
            ->leftJoin('finance_wallet', 'finance_wallet.user_id', '=', $this->table . '.user_id')
            ->orderBy('create_time', $sort)
            ->paginate($limit, [$this->table . '.*', 'user.uuid as user_uuid', 'union_user.un_id', 'union.name as union_name', 'finance_wallet.wealth_balance'], 'page', $page);
        $dataArray = $data->toarray();
        $data_userid = array_column($dataArray['data'], 'user_id');
        $data_user = array_column($dataArray['data'], null, 'user_id');
        $timeint = DB::connection('statistic')->table($this->login_table)
            ->whereIn('user_id', $data_userid)
            ->groupBy('user_id')
            ->select(DB::raw("max(create_at) as last_login_time,user_id"))
            ->get();
        //        var_dump($timeint);
        if ($timeint) {
            $timeArr = $timeint->toArray();
            $time_user = array_column($timeArr, null, 'user_id');
        }
        $finance_rant = DB::connection($this->connection)->table($this->finance_rant)
            ->where('rank_pid', 0)
            ->select(DB::raw('min_value,max_value,rank_name'))
            ->get();
        $union_signing = DB::connection($this->connection)->table($this->union_signing)
            ->whereIn('user_id', $data_userid)
            ->leftJoin('union', 'union.id', '=', $this->union_signing . '.un_id')
            ->select($this->union_signing . ".un_id", $this->union_signing . ".user_id", $this->union_signing . ".expire_time", $this->union_signing . ".created_at", "union.name")
            ->get();
        $setInfo = DB::connection($this->connection)->table($this->set_table)
            ->whereIn('user_id', $data_userid)
            ->get();

        if ($union_signing) {
            $signArr = $union_signing->toArray();
            $signUser = array_column($signArr, null, 'user_id');
        }

        if ($setInfo) {
            $setInfoArr = $setInfo->toArray();
            $setInfoMap = array_column($setInfoArr, null, 'user_id');
        }
        foreach ($data as $k => $v) {
            if ($time_user && array_key_exists($v->user_id, $time_user)) {
                $data[$k]->last_login_time = $time_user[$v->user_id]->last_login_time;
            }
            if (!empty($signUser)) {
                $data[$k]->sign_create_time = array_key_exists($v->user_id, $signUser) ? $signUser[$v->user_id]->created_at : '';
                $data[$k]->sign_expire_time = array_key_exists($v->user_id, $signUser) ? $signUser[$v->user_id]->expire_time : '';
                $data[$k]->sign_union_name = array_key_exists($v->user_id, $signUser) ? $signUser[$v->user_id]->name : '';
                $data[$k]->sign_state = $data[$k]->sign_expire_time > time() ? 1 : 0;
            }

            $data[$k]->v_start_time = $setInfoMap[$v->user_id]->v_start_time ?? 0;
            $data[$k]->v_end_time = $setInfoMap[$v->user_id]->v_end_time ?? 0;

            $data[$k]->rank_name = '';
            foreach ($finance_rant as $vel) {
                if ($v->wealth_balance >= $vel->min_value && $v->wealth_balance <= $vel->max_value) {
                    $data[$k]->rank_name = $vel->rank_name;
                    continue;
                }
            }

        }
        return $data;
        //        return $query->whereNotBetween('uuid', [11, 14])
//            ->with(['activeCertifyModel'])
//            ->orderBy('create_time', $sort)
//            ->paginate($limit, $this->fields, 'page', $page);
    }

    public function getNicknameByUserId($user_id)
    {
        return self::where('user_id', $user_id)->first('nickname');
    }
    public function getInfoByUserId($user_id)
    {
        $res = self::where('uuid', $user_id)->first();
        return $this->objToArray($res);
    }

    public function getRegisterStatistics($limit, $page)
    {
        $data = $this->registerStatistics($limit, $page);
        $limitdata = [];
        $returndata = [];
        $total = [
            'count' => 0,
            'boy' => 0,
            'girl' => 0,
            '_80q' => 0,
            '_80h' => 0,
            '_90h' => 0,
            '_00h' => 0,
            '_10h' => 0,
            'ios' => 0,
            'android' => 0
        ];
        foreach ($data['data'] as $k => $v) {
            $v = collect($v)->toArray();
            $limitdata[] = $v;
            $total['count'] = $total['count'] + $v['count'];
            $total['boy'] = $total['boy'] + $v['boy'];
            $total['girl'] = $total['girl'] + $v['girl'];
            $total['_80q'] = $total['_80q'] + $v['80q'];
            $total['_80h'] = $total['_80h'] + $v['80h'];
            $total['_90h'] = $total['_90h'] + $v['90h'];
            $total['_00h'] = $total['_00h'] + $v['00h'];
            $total['_10h'] = $total['_10h'] + $v['10h'];
            $total['ios'] = $total['ios'] + $v['ios'];
            $total['android'] = $total['android'] + $v['android'];
        }

        $returndata['data'] = $limitdata;
        //        $returndata['count'] = count($data);
        $returndata['total'] = $data['total'];
        $returndata['allTotal'] = $data['allTotal'];
        return $returndata;
    }

    /**
     * 注册统计
     * @param int $limit
     * @param int $page
     * @return array
     */
    private function registerStatistics(int $limit, int $page)
    {
        DB::connection()->disableQueryLog();

        // 总数
        $total = DB::connection('api')->selectOne("SELECT COUNT(DISTINCT created_at) AS total FROM (SELECT FROM_UNIXTIME(create_timestamp,'%Y-%m-%d') as created_at FROM zb_user GROUP BY created_at) AS t");

        $data = DB::connection('api')->select('select count(*) as count,
        FROM_UNIXTIME(create_timestamp,\'%Y-%m-%d\')as date,
        sum(case when gender=1 then 1 else 0 end) as boy,
        sum(case when gender=2 then 1 else 0 end) as girl,
        sum(case when FROM_UNIXTIME(birthday,\'%Y\') <1990 and FROM_UNIXTIME(birthday,\'%Y\') >1979 then 1 else 0 end) as 80h,
        sum(case when FROM_UNIXTIME(birthday,\'%Y\') <2000 and FROM_UNIXTIME(birthday,\'%Y\') >1989 then 1 else 0 end) as 90h,
        sum(case when FROM_UNIXTIME(birthday,\'%Y\') <2010 and FROM_UNIXTIME(birthday,\'%Y\') >1999 then 1 else 0 end) as 00h,
        sum(case when FROM_UNIXTIME(birthday,\'%Y\') >2010 then 1 else 0 end) as 10h,
        sum(case when FROM_UNIXTIME(birthday,\'%Y\') <1980 then 1 else 0 end) as 80q,
        sum(case when channel_id<10000 then 1 else 0 end) as ios,
        sum(case when channel_id>=10000 then 1 else 0 end) as android
        from zb_user GROUP BY FROM_UNIXTIME(create_timestamp,\'%Y-%m-%d\' ) ORDER BY date desc LIMIT ' . ($page - 1) * $limit . ',' . $limit);

        $allTotal['count'] = array_sum(array_column($data, 'count'));
        $allTotal['boy'] = array_sum(array_column($data, 'boy'));
        $allTotal['girl'] = array_sum(array_column($data, 'girl'));
        $allTotal['h80'] = array_sum(array_column($data, '80h'));
        $allTotal['h90'] = array_sum(array_column($data, '90h'));
        $allTotal['h00'] = array_sum(array_column($data, '00h'));
        $allTotal['h10'] = array_sum(array_column($data, '10h'));
        $allTotal['q80'] = array_sum(array_column($data, '80q'));
        $allTotal['ios'] = array_sum(array_column($data, 'ios'));
        $allTotal['android'] = array_sum(array_column($data, 'android'));
        return ['data' => $data, 'total' => $total->total, 'allTotal' => $allTotal];
    }

    /**
     * 获取被屏蔽的用户
     * @return array
     */
    public function getForbidList()
    {
        $kkaudio_api = config('kkaudio.kkaudio_api');
        // 获取屏蔽列表
        $curl_res = curl_request($kkaudio_api . '/inner/user/forbid_list', '', 'json', 'GET');
        $forbid_list = [];
        if ($curl_res['code'] == 0) {
            $forbid_list = array_filter($curl_res['data'] ?? [], function ($timestamp) {
                if ('0' === $timestamp)
                    return true;
                if ($timestamp > time())
                    return true;
            });
        }
        $this->forbidUser = $forbid_list;
    }

    public function getUserByForbidUser(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $uuid = $request->input('uuid');
        $nickname = $request->input('nickname');
        $this->getForbidList();
        if (empty($this->forbidUser))
            return [];

        $user_id = array_keys($this->forbidUser);
        $query = new self();

        $query = $query->whereIn('user_id', $user_id);
        if ($uuid)
            $query = $query->where('uuid', $uuid);
        if ($nickname)
            $query = $query->where('nickname', 'LIKE', "{$nickname}%");

        return $query->paginate($limit, ['*'], 'page', $page);
    }

    public function uuidIsSet($uuid)
    {
        return self::where('uuid', $uuid)->count();
    }

    /**
     * 设置 UUID
     * @param int $user_id
     * @param int $uid
     * @return bool
     */
    public function setUUID(int $user_id, int $uid)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/user/set_uid', ['user_id' => $user_id, 'uid' => $uid]);
    }

    /**
     * Created at 2021/12/10 11:57
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param string $old_uuid
     * @param string $uuid
     * @param $endDate
     * @param int $operatorUserId
     * @param string $operatorUserName
     * @return mixed
     */
    public function setUUIDV2(string $old_uuid, string $uuid, $endDate, int $operatorUserId, string $operatorUserName)
    {
        return curl_request(
            getKkaudioApiUrl() . '/inner/cool_number/change_user_uuid',
            ['old_uuid' => $old_uuid, 'uuid' => $uuid, 'end_date' => $endDate, 'operator_user_id' => $operatorUserId, 'operator_user' => $operatorUserName]
        );
    }

    /**
     * 设置巡房(接待)
     * @param $user_id
     * @param $waiter 0. 非接待 1. 接待
     * @return bool
     */
    public function setWaiter($user_id, $waiter)
    {
        $res = curl_request(getKkaudioApiUrl() . '/inner/user/set_waiter', ['user_id' => $user_id, 'waiter' => $waiter]);
        if ($res['code'] == 0) {
            return true;
        }
        return false;
    }

    /**
     * 设置官方
     * @param $user_id
     * @param $official 0. 非官方 1. 官方
     * @return bool
     */
    public function setOfficial($user_id, $official)
    {
        $res = curl_request(getKkaudioApiUrl() . '/inner/user/set_official', ['user_id' => $user_id, 'official' => $official]);
        if ($res['code'] == 0) {
            return true;
        }
        return false;
    }

    /**
     * 设置超管
     * @param int $user_id
     * @param int $super 0. 非超管 1. 超管
     * @return bool
     */
    public function setSuper(int $user_id, int $super)
    {
        $res = curl_request(getKkaudioApiUrl() . '/inner/user/set_super', ['user_id' => $user_id, 'super' => $super]);
        if ($res['code'] == 0) {
            return true;
        }
        return false;
    }

    /**
     * 设置靓号
     * @param int $user_id
     * @param int $liang 0.非靓号 1.靓号
     * @return bool
     */
    public function setGoodMobileNumber(int $user_id, int $liang)
    {
        $res = curl_request(getKkaudioApiUrl() . '/inner/user/set_liang', ['user_id' => $user_id, 'liang' => $liang]);
        if ($res['code'] == 0) {
            return true;
        }
        return false;
    }

    public function getNicknameByUserIds(array $user_ids)
    {
        if (empty($user_ids))
            throw new \Exception('参数错误');
        return self::whereIn('user_id', $user_ids)->get(['user_id', 'nickname', 'UUID'])->toArray();
    }
    public function getNicknameUUidByUserIds($user_ids)
    {
        if (empty($user_ids))
            throw new \Exception('参数错误');
        return self::whereIn('user_id', $user_ids)->get(['user_id', 'uuid', 'nickname'])->toArray();
    }

    public function getPrice($user_id)
    {
        $res = DB::connection($this->connection)->table($this->table)->where(['user_id' => $user_id])->select('portrait')->first();
        $data = json_decode($res->portrait);
        if (empty($data))
            return [];
        $price = [];
        foreach ($data as $k => $value) {
            $price[$k]['price_key'] = $k;
            if (!empty($value)) {
                $price[$k]['price_value'] = build_image(getUrlPath($value));
            }
        }
        return $price;
    }

    //删除照片墙照片
    public function delPriceWall($request)
    {
        $data = $request->all();
        $res = DB::connection($this->connection)->table($this->table)->where(['user_id' => $data['user_id']])->select('portrait')->first();
        $portrait = json_decode($res->portrait);
        unset($portrait[$data['price_key']]);
        if (empty($portrait))
            $portrait[] = config('kkaudio.oss_url') . Number::DEFAULT_HEAD_IMG;
        $delData['user_id'] = $data['user_id'];
        $delData['portrait'] = json_encode(array_values($portrait));
        $curl = curl_request(getKkaudioApiUrl() . '/inner/user/edit/user_info', $delData, 'urlencoded', 'GET');
        if ($curl['code'] == 0) {
            return true;
        }
        return false;
    }

    public function userSign($user_id)
    {
        return DB::connection($this->connection)->table($this->table)->where(['user_id' => $user_id])->select('uuid', 'sign')->first();
    }

    public function editUserSign($request)
    {
        $data['user_id'] = $request->input('user_id');
        $data['sign'] = $request->input('sign');
        $curl = curl_request(getKkaudioApiUrl() . '/inner/user/edit/user_info', $data, 'urlencoded', 'GET');
        if ($curl['code'] == 0) {
            return true;
        }
        return false;
    }

    public function setUserV($request)
    {
        $data['user_id'] = $request->input('user_id');
        $data['v_desc'] = $request->input('desc');
        $data['v'] = $request->input('v') ?? 1;
        $data['start_time'] = $request->input('start_time') ?? 0;
        $data['end_time'] = $request->input('end_time') ?? 0;
        $curl = curl_request(getKkaudioApiUrl() . '/inner/user/set_v', $data);
        if ($curl['code'] == 0) {
            return true;
        }
        return false;
    }

    /**
     * 设置用用账号异常
     * @param Request $request
     * @param $user_id
     * @param $is_abnormal 0,正常;1,异常
     * @return mixed
     */
    public function setAbnormal(Request $request, $user_id, $is_abnormal)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/user/set_abnormal', ['user_id' => $user_id, 'is_abnormal' => $is_abnormal], 'json', 'POST');
    }


    //查询用户头像记录
    public function getAuditUserImg($page = 1, $limit = 300, $start_date, $end_date)
    {
        $list = DB::connection($this->connection)->table($this->table)->whereBetween('updated_at', [$start_date, $end_date])->paginate($limit, ['user_id', 'portrait', 'school', 'sign', 'voice'], 'page', $page);
        $list = $this->objToArray($list);
        return $list['data'];
    }

    public function getAuditUserLog($input = [])
    {
        $limit = $input['limit'] ?? 200;
        $img_type = $input['img_type'] ?? 0;
        $list = DB::table($this->audit_table)->where(['img_type' => $img_type])->orderBy('id', 'desc')->paginate($limit);
        return $this->objToArray($list);
    }

    public function getAuditUserTextLog($input = [])
    {
        $limit = $input['limit'] ?? 500;
        $w_type = $input['type'] ?? 'sign_type';
        $where[$w_type] = 0;
        $list = DB::table($this->audit_table)->where($where)->orderBy('id', 'desc')->paginate($limit);
        return $this->objToArray($list);
    }

    public function getAuditUserVoiceLog($input = [])
    {
        $limit = $input['limit'] ?? 500;
        $where['voice_type'] = 0;
        $where[] = ['voice', '!=', ''];
        $list = DB::table($this->audit_table)->where($where)->orderBy('id', 'desc')->paginate($limit);
        return $this->objToArray($list);
    }

    public function setAuditUserImgType($ids, $type = 2, $set_type = 1)
    {
        $data = [];
        switch ($set_type) {
            case 1://img
                $data['img_type'] = $type;
                break;
            case 2://img
                $data['school_type'] = $type;
                $data['sign_type'] = $type;
                break;
            case 3:
                $data['voice_type'] = $type;
                break;
        }
        return DB::table($this->audit_table)->whereIn('id', $ids)->update($data);

    }

    public function getInviteUser($input = [])
    {
        $limit = $input['limit'] ?? 20;
        $where['invite_uid'] = $input['user_id'];
        $res = DB::connection($this->connection)->table($this->table)->where($where)->paginate($limit);
        return $this->objToArray($res);

    }

    public function getRechargeLimitList($request)
    {

        $page = $request['page'] ?? 0;
        $limit = $request['limit'] ?? 10;

        $uuid = $request['uuid'] ?? 0;
        $nickname = $request['nickname'] ?? 0;
        $query = DB::connection($this->connection)->table($this->recharge_limit_table);

        if ($uuid)
            $query = $query->where('user.uuid', $uuid);
        if ($nickname)
            $query = $query->where('user.nickname', 'like', "%$nickname%");
        return $query->leftJoin('user', 'user.user_id', '=', 'user_recharge_limit.user_id')
            ->orderBy('user_recharge_limit.created_time', 'desc')
            ->paginate($limit, ['user.uuid as uuid', 'user.user_id as user_id', 'user.nickname as nickname', 'user_recharge_limit.id', 'user_recharge_limit.value as value', 'user_recharge_limit.created_time as created_time', 'user_recharge_limit.status'], 'page', $page);

    }

    public function curdRechargeLimit($data)
    {
        $res = curl_request(getKkaudioApiUrl() . '/inner/user/curd_recharge_limit', $data, 'json', 'POST');
        if ($res['code'] == 0) {
            return true;
        }
        return false;
    }
    public function delRechargeLimit($id)
    {
        $res = curl_request(getKkaudioApiUrl() . '/inner/user/del_recharge_limit', array('id' => $id), 'urlencoded', 'GET');
        if ($res['code'] == 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取同设备下所有账号
     * @param $guid  手机唯一标识
     */
    public function banned($input, $guid)
    {
        $data = [];
        $limit = $input['limit'] ?? 10;
        $list = DB::connection($this->connection)->table('user')
            ->where(['guid' => $guid])
            ->select('user_id', 'uuid', 'nickname')->paginate($limit);
        $data['list'] = $list;

        $deviceInfo = DB::connection($this->connection)->table('device')
            ->where('guid', '=', $guid)
            ->select('version_no', 'os_name', 'device', 'created_at', 'guid')
            ->get();
        $deviceInfo = $this->objToArray($deviceInfo);
        foreach ($deviceInfo as $k => $v) {
            $deviceInfo[$k]['created_at'] = date('Y-m-d H:i:s', $v['created_at']);
        }

        //获取设备封禁状态
        $res = curl_request(getKkaudioApiUrl() . '/inner/user/forbid_device', array('guid' => $guid), 'urlencoded', 'GET');
        $data['device'] = $deviceInfo;
        $data['device'][0]['forbid_status'] = $res;
        return $data;

    }

    public function resetDevice($user_id)
    {
        $res = curl_request(getKkaudioApiUrl() . '/inner/user/resetDevice', array('user_id' => $user_id), 'urlencoded', 'GET');
        return $res;
    }

    /**
     * 获取用实名下所有账号
     * @param $input
     * @param $userId
     */
    public function verifyList($input, $userId)
    {
        $data = [];
        $limit = $input['limit'] ?? 10;

        $verifyInfo = DB::connection($this->connection)->table('user_verify')
            ->where(['user_id' => $userId])
            ->select('idcard_number', 'idcard_name')
            ->first();

        if ($verifyInfo) {
            $list = DB::connection($this->connection)->table('user_verify')
                ->where('idcard_number', '=', $verifyInfo->idcard_number)
                ->where('result_code', '=', 1000)
                ->groupBy('user_id')
                ->select('user_id')
                ->paginate($limit);
            $list = $this->objToArray($list);
            $user_ids = array_column($list['data'], 'user_id');
            $user = DB::connection($this->connection)->table('user')
                ->whereIn('user_id', $user_ids)
                ->select('uuid', 'nickname', 'user_id', 'mobile_phone')
                ->get()->toArray();
            $user = array_column($user, null, 'user_id');
            foreach ($list['data'] as $k => $v) {
                $res = curl_request(getKkaudioApiUrl() . '/inner/user/forbid_status', array('user_id' => $v['user_id']), 'urlencoded', 'GET');
                $list['data'][$k]['forbid_status'] = $res;
                $list['data'][$k]['idcard_number'] = $verifyInfo->idcard_number;
                $list['data'][$k]['idcard_name'] = $verifyInfo->idcard_name;
                $list['data'][$k]['uuid'] = isset($user[$v['user_id']]) ? $user[$v['user_id']]->uuid : 0;
                $list['data'][$k]['nickname'] = isset($user[$v['user_id']]) ? $user[$v['user_id']]->nickname : '';
                $list['data'][$k]['mobile_phone'] = isset($user[$v['user_id']]) ? $user[$v['user_id']]->mobile_phone : '';

            }
            $data['list'] = $list;

            return $data;
        }
    }

    public function clearVerify($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/user/clear_verify', $data, 'urlencoded', 'POST');
    }

    public function clearUserAll($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/user_verify/clearUserAll', $data, 'urlencoded', 'POST');
    }

    public function clearUserbankAll($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/finance/clearUserbankAll', $data, 'urlencoded', 'POST');
    }

    public function getUserByUserIDs($user_ids)
    {
        $res = DB::connection($this->connection)->table($this->table)
            ->whereIn('user_id', $user_ids)
            ->get(['nickname', 'user_id', 'uuid', 'portrait']);
        return $this->objToArray($res);

    }

    public function getUserByUuid($uuid)
    {
        $res = DB::connection($this->connection)->table($this->table)
            ->where('uuid', $uuid)
            ->first(['nickname', 'user_id', 'uuid', 'portrait']);

        $info = $this->objToArray($res);
        if (!empty($info)) {
            $info['portrait'] = $this->build_images($info['portrait']);
        }
        return $info;
    }

    public function getUserByUuids($uuids)
    {
        $res = DB::connection($this->connection)->table($this->table)
            ->whereIn('uuid', $uuids)
            ->get(['nickname', 'user_id', 'uuid', 'portrait']);
        return $this->objToArray($res);
    }

    /**
     * 注销用户
     * @param $user_id
     */
    public function userCancel($user_id)
    {
        $res = curl_request(getKkaudioApiUrl() . '/inner/user/simpleAccountCancel', array('user_id' => $user_id));
        return $res;
    }

    public function getUserLoginLog($user_id, $start_time = 0, $end_time = 0, $page = 1, $limit = 30)
    {
        $query = DB::connection($this->connection)
            ->table($this->user_lgoin_log_table)
            ->where($this->user_lgoin_log_table . '.user_id', '=', $user_id);
        if ($start_time) {
            $query = $query->where($this->user_lgoin_log_table . '.time', '>=', $start_time);
        }
        if ($end_time) {
            $query = $query->where($this->user_lgoin_log_table . '.time', '<=', $end_time);
        }
        $list = $query->paginate($limit, ['*'], 'page', $page);
        $data = $list->items();
        $data = $this->objToArray($data);
        $data = curl_request(getKkaudioApiUrl() . '/inner/user/forbid_ip_list', array('data' => $data),'json', 'POST');
        $list = $data;
        return $this->objToArray($list);
    }

    /**
     * 添加图片url列表
     * @param $portrait_json
     * @return array
     */
    public function build_images($portrait_json)
    {
        $portrait = json_decode($portrait_json, true);
        $images = [];
        if ($portrait) {
            foreach ($portrait as $k => $v) {
                if (strtolower(substr($v, 0, 4)) == "http") {
                    $images[$k] = $v;
                } else {
                    $images[$k] = $this->getOSSUrl() . $v;
                }

            }
        }
        return $images;
    }

    public function activateCodeList($input)
    {
        $limit = $input['limit'] ?? 10;
        $page = $input['page'] ?? 1;
        $where = ' 1';
        $uuid = $input['uuid'] ?? '';

        $query = DB::connection($this->connection)->table($this->table)
            ->where('is_open_code', 1);
        if (!empty($uuid)) {
            $query = $query->where('uuid', $uuid);
        }
        if (!empty($nickname)) {
            $query = $query->where('nickname', 'like', '%' . $nickname . '%');
        }
        $data = $query->paginate($limit, '*', 'page', $page);
        $data = $this->objToArray($data);

        return ['total' => $data['total'], 'data' => $data['data'], 'current_page' => intval($page)];
    }


}
